06 / 06

What is the purpose of Class attribute? How is it different from ID?

Class vs ID Attributes in HTML

The class attribute in HTML is used to assign one or more class names to an element. These class names can be targeted with CSS or JavaScript to style or manipulate multiple elements at once.

The id attribute is used to assign a unique identifier to a single element. It is intended to be unique within a page and is often used to target a specific element with CSS or JavaScript.

Key Differences Between class and id
  1. 1

    Uniqueness: id must be unique in a page, while class can be shared by multiple elements.

  2. 2

    Usage: class is typically used for styling multiple elements; id is used for targeting a single element.

  3. 3

    CSS Selector: #idName targets an id, .className targets a class.

  4. 4

    JavaScript Access: document.getElementById() for id, document.getElementsByClassName() for class.

Example Usage

In short: Use class to apply styles or scripts to multiple elements, and id to target a unique element on the page.